package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net-video-mgr/cache"
	"net-video-mgr/model"
	"net-video-mgr/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码不正确",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func List(c *gin.Context) {
	var article []model.Article
	redis_key := "redis_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var article model.Article

	redis_key := "redis_detail_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}

func Like(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	aid, _ := strconv.Atoi(c.PostForm("aid"))
	data := model.Like{
		Uid: uid,
		Aid: aid,
	}
	var like model.Like
	err := model.DB.Where("uid = ? and aid = ?", uid, aid).First(&like).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不能重复点赞",
		})
		return
	}
	err = model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "点赞失败",
		})
		return
	}
	var article model.Article
	err = model.DB.Save(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "更新失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	return
}
